package org.millioncall.yueyoga.admin.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperRunManager;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.Pager;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.NumberUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.export.AbstractExcelExportTemplate;
import org.millioncall.yueyoga.admin.export.ConsumeHistoryExportTemplate;
import org.millioncall.yueyoga.admin.export.ProductExportTemplate;
import org.millioncall.yueyoga.admin.export.TinyOrderExportTemplate;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.admin.model.ClassMemberModel;
import org.millioncall.yueyoga.admin.model.ConsumeHistoryModel;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.Order;
import org.millioncall.yueyoga.admin.model.OrderDetail;
import org.millioncall.yueyoga.admin.model.Product;
import org.millioncall.yueyoga.admin.model.ProductRemaining;
import org.millioncall.yueyoga.admin.model.ProductUsedInfo;
import org.millioncall.yueyoga.admin.model.Recharge;
import org.millioncall.yueyoga.admin.model.Remaining;
import org.millioncall.yueyoga.admin.model.Site;
import org.millioncall.yueyoga.admin.model.Status;
import org.millioncall.yueyoga.admin.model.TinyClass;
import org.millioncall.yueyoga.admin.model.TinyOrderModel;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.ClazzService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.OrderDetailService;
import org.millioncall.yueyoga.admin.service.OrderService;
import org.millioncall.yueyoga.admin.service.ProductRemainingService;
import org.millioncall.yueyoga.admin.service.ProductService;
import org.millioncall.yueyoga.admin.service.RechargeService;
import org.millioncall.yueyoga.admin.service.RemainingService;
import org.millioncall.yueyoga.admin.service.StatusService;
import org.millioncall.yueyoga.admin.service.SystemService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.millioncall.yueyoga.common.utils.FrontUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

@Controller
public class ProductAction extends BaseAction {
	private UserService userService;
	private OrderService orderService;
	private MemberService memberService;
	private ProductService productService;
	private RemainingService remainingService;
	private OrderDetailService orderDetailService;
	private ProductRemainingService productRemainingService;
	private ClazzService clazzService;
	private StatusService statusService;
	private SystemService systemService;
	private RechargeService rechargeService;

	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	private DateTimeUtils dtu = DateTimeUtils.getInstance();

	@RequestMapping(value = "ajaxDelayProductValidDays.jhtml")
	public void ajaxDelayProductValidDays(HttpServletRequest request,
			HttpServletResponse response) {
		String memberId = request.getParameter("memberId");
		String remainingId = request.getParameter("remainingId");
		String delayDays = request.getParameter("delayDays");
		int realDays = 0;
		try {
			realDays = Integer.valueOf(delayDays);
		} catch (NumberFormatException e) {
			WebAppUtils.ajaxResponse(response, "{\"success\":false}");
		}

		ProductRemaining pr = this.productRemainingService
				.findProductRemainingById(Integer.valueOf(remainingId));
		Date end = pr.getEndTime();
		Calendar can = Calendar.getInstance();
		can.setTime(end);
		can.add(Calendar.DAY_OF_MONTH, realDays);
		pr.setEndTime(can.getTime());

		boolean b = this.productRemainingService.updateProductRemaining(pr);
		if (b) {
			WebAppUtils.ajaxResponse(response, "{\"success\":true}");
		}
	}

	/** 高级搜索产品 */
	@RequestMapping(value = "/ajaxAdvSearchProducts.jhtml")
	public void advSearchMember(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String strLimit = request.getParameter("limit");

		String exp = request.getParameter("expression");
		String expType = request.getParameter("expType");

		String msg = "";

		int limit = Integer.MAX_VALUE;

		try {
			limit = Integer.parseInt(strLimit);
		} catch (NumberFormatException e) {
			limit = Integer.MAX_VALUE;
		}

		if (StringUtils.isBlank(exp)) {
			msg = "{'success':false, 'msg':'表达式不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (StringUtils.isBlank(expType)) {
			msg = "{'success':false, 'msg':'表达式类型不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		// 用于过滤会员的条件map
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hallcode", this.getUser(request).getOrganizationId());

		// 条件表达式
		// 在此组装条件表达式
		AviatorExpression expression = new AviatorExpression();
		expression.setExpression(exp);
		// 条件表达式的map
		Map<String, Object> aviatorParams = new HashMap<String, Object>();
		aviatorParams.put(GlobalConstants.RESULT_ROW_MODEL_KEY, expType);

		List<Product> products = this.productService.getAllProductsWithAviator(
				params, expression, aviatorParams, limit);

		if (products.size() > 0) {
			String json = JSON.toJSONStringWithDateFormat(products,
					"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
			msg = "{'success':true, 'total':'" + products.size()
					+ "', 'items':" + json + "}";
		} else {
			msg = "{'success':true, 'total':'0', 'items':''}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 删除产品 */
	@RequestMapping(value = "/deleteProductsByIds.jhtml")
	public void deleteProduct(String ids, HttpServletResponse response) {
		String msg = null;
		if (StringUtils.isBlank(ids)) {
			msg = "false";
		} else {
			if (this.productService.deleteByIds(ids.split(",")) > 0) {
				msg = "true";
			} else {
				msg = "false";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * ajax获取消费记录
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/ajaxGetConsumeList.jhtml", method = RequestMethod.POST)
	public void ajaxGetConsumeList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {
		String classId = request.getParameter("classId");
		String productId = request.getParameter("productId");
		String memberId = request.getParameter("memberId");
		String areaId = request.getParameter("areaId");
		String consumeTimeFrom = request.getParameter("consumeTimeFrom");
		String consumeTimeTo = request.getParameter("consumeTimeTo");
		String scheduleTimeFrom = request.getParameter("scheduleTimeFrom");
		String scheduleTimeTo = request.getParameter("scheduleTimeTo");
		String totalAbsent = request.getParameter("totalAbsent");

		Map<String, Object> params = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(classId)) {
			params.put("classId", classId);
		}

		if (StringUtils.isNotBlank(productId)) {
			params.put("productId", productId);
		}

		if (StringUtils.isNotBlank(memberId)) {
			params.put("memberId", memberId);
		}

		if (StringUtils.isNotBlank(areaId)) {
			params.put("areaId", areaId);
		}

		if (StringUtils.isNotBlank(consumeTimeFrom)) {
			params.put("consumeTimeFrom", consumeTimeFrom);
		}

		if (StringUtils.isNotBlank(consumeTimeTo)) {
			params.put("consumeTimeTo", consumeTimeTo);
		}

		if (StringUtils.isNotBlank(scheduleTimeFrom)) {
			params.put("scheduleTimeFrom", scheduleTimeFrom);
		}
		if (StringUtils.isNotBlank(scheduleTimeTo)) {
			params.put("scheduleTimeTo", scheduleTimeTo);
		}

		if (StringUtils.isNotBlank(totalAbsent)) {
			params.put("totalAbsent", totalAbsent);
		}

		if (pageNo == null) {
			pageNo = 1;
		}

		if (pageSize == null) {
			pageSize = 10;
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);

		PaginatedList<ConsumeHistoryModel> consumeList;
		if (StringUtils.isBlank(totalAbsent)) {
			consumeList = this.productService.findAllConsumeHistory(params,
					pageNo, pageSize);
		} else {
			consumeList = this.productService.findAllAbsentForSomeDays(params,
					pageNo, pageSize);
		}

		Pager pager = consumeList.getPager();

		String consumeItems = JSON.toJSONString(consumeList);
		String json = "{'success':true,totalPages:"
				+ pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:"
				+ pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:"
				+ pager.getNextPageNo() + ",items:" + consumeItems + "}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/**
	 * ajax获取产品记录
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/ajaxGetProductList.jhtml", method = RequestMethod.POST)
	public void ajaxGetProductList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {

		int start = 0;
		// 产品的查询条件
		String productName = request.getParameter("productName");
		String productType = request.getParameter("productType");
		String startdate1 = request.getParameter("startdate1");
		String startdate2 = request.getParameter("startdate2");
		String enddate1 = request.getParameter("enddate1");
		String enddate2 = request.getParameter("enddate2");

		Map<String, Object> params = new HashMap<String, Object>();

		if (pageSize == null) {
			pageSize = 10;
		}

		if (pageNo != null) {
			start = (pageNo - 1) * pageSize;
		}

		if (StringUtils.isNotBlank(productName)) {
			params.put("name", productName);
		}
		if (StringUtils.isNotBlank(productType)) {
			params.put("type", productType);
		}

		if (StringUtils.isNotBlank(startdate1)) {
			params.put("startdate1", startdate1);
		}

		if (StringUtils.isNotBlank(enddate1)) {
			params.put("enddate1", enddate1);
		}

		if (StringUtils.isNotBlank(startdate2)) {
			params.put("startdate2", startdate2);
		}

		if (StringUtils.isNotBlank(enddate2)) {
			params.put("enddate2", enddate2);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);
		params.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Product> pl = productService.findInPage(params, start,
				pageSize);
		model.put("products", pl);

		String productItems = JSON.toJSONString(pl);
		Pager pager = pl.getPager();
		String json = "{'success':true,totalPages:"
				+ pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:"
				+ pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:"
				+ pager.getNextPageNo() + ",items:" + productItems + "}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/**
	 * ajax获取购买记录
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/ajaxGetOrderList.jhtml", method = RequestMethod.POST)
	public void ajaxGetOrderList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {

		// 购买记录的查询条件
		String orderProName = request.getParameter("orderProName");
		String orderProType = request.getParameter("orderProType");
		String buyStartDate = request.getParameter("buyStartDate");
		String buyEndDate = request.getParameter("buyEndDate");
		String buyerId = request.getParameter("buyerId");
		String sellerId = request.getParameter("sellerId");
		String orderType = request.getParameter("orderType");

		Map<String, Object> params = new HashMap<String, Object>();

		if (pageNo == null) {
			pageNo = 1;
		}

		if (pageSize == null) {
			pageSize = 10;
		}
		if (StringUtils.isNotBlank(orderProName)) {
			params.put("name", orderProName);
		}
		if (StringUtils.isNotBlank(orderProType)) {
			params.put("type", orderProType);
		}
		if (StringUtils.isNotBlank(sellerId)) {
			params.put("sellerId", sellerId);
		}
		if (StringUtils.isNotBlank(buyerId)) {
			params.put("buyerId", buyerId);
		}
		if (StringUtils.isNotBlank(buyStartDate)) {
			params.put("buyStartDate", buyStartDate);
		}
		if (StringUtils.isNotBlank(buyEndDate)) {
			params.put("buyEndDate", buyEndDate);
		}
		if (StringUtils.isNotBlank(orderType)) {
			params.put("orderType", orderType);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);
		PaginatedList<TinyOrderModel> pl = this.orderService.findAllBuyRecord(
				pageNo, pageSize, params);
		String orderItems = JSON.toJSONString(pl);
		System.out.println(orderItems);
		Pager pager = pl.getPager();
		String json = "{'success':true,totalPages:"
				+ pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:"
				+ pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:"
				+ pager.getNextPageNo() + ",items:" + orderItems + "}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 查询产品 **/
	@RequestMapping(value = "/searchProducts.jhtml")
	public String findProductsByConditions(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);

		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		User user = super.getUser(request);

		String dis = request.getParameter("dis");
		if ("1".equals(dis)) {
			model.put("dis", dis);
		}
		// 查询负责人
		List<GroupUserModel> respors = this.userService.findUsersByGroupId("4",
				user.getOrganizationId());
		model.put("respors", respors);

		// 查询会员（购买人）
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("key", "organizationId");
		map1.put("value", user.getOrganizationId());
		map1.put("groups", groupIds);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		List<Member> members = memberService.findMemberByProperty(map1);
		model.put("members", members);

		/*
		 * 产品消费记录部分
		 */
		// 查询所有班级
		List<TinyClass> classList = this.clazzService.findAllClassTiny(map);
		model.put("classList", classList);
		// 查询所有产品
		Map<String, Object> mapP = new HashMap<String, Object>();
		mapP.put("groups", groupIds);
		mapP.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> productList = this.productService
				.findProductAvailableAll(mapP);
		model.put("productList", productList);
		// 所有会员

		List<ClassMemberModel> allMembers = this.memberService
				.findAllBasicMemberInfo(map);
		model.put("consumeMembers", allMembers);
		return "product_search";
	}

	@RequestMapping(value = "/toAddProduct.jhtml")
	public String toAddProduct(HttpServletRequest request, ModelMap map) {
		super.initFrontHeader(request, map);
		return "product_add";
	}

	@RequestMapping(value = "/toEditProduct.jhtml")
	public String toEditProduct(String productId, HttpServletRequest request,
			ModelMap map) {
		super.initFrontHeader(request, map);
		if (StringUtils.isNotBlank(productId)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("productId", productId);
			List<Integer> groupIds = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds.add(group.getId());
			}
			params.put("groups", groupIds);
			params.put("hallcode", this.getUser(request).getOrganizationId());
			map.put("product", productService.findById(params));
		}
		return "product_edit";
	}

	// --产品明细
	@RequestMapping(value = "/toProductDetails.jhtml")
	public String toProductDetails(String productId,
			HttpServletRequest request, ModelMap map) {
		super.initFrontHeader(request, map);
		if (StringUtils.isNotBlank(productId)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("productId", productId);
			List<Integer> groupIds = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds.add(group.getId());
			}
			params.put("groups", groupIds);
			params.put("hallcode", this.getUser(request).getOrganizationId());
			map.put("product", productService.findById(params));
		}
		return "product_mingxi";
	}

	// --保存
	@RequestMapping(value = "/addProduct.jhtml")
	public String addProduct(String productId, String name, String type,
			String price, String beginTime, String endTime, String counts,
			String remarks, HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);
		Map<String, Object> map = new HashMap<String, Object>();
		User user = this.getUser(request);
		Product product = new Product();
		product.setOrganizationId(user.getOrganizationId());
		product.setCounts(0);
		// --产品状态默认可用
		product.setEnable(1);
		// 是否为修改
		if (StringUtils.isNotBlank(productId)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("productId", productId);
			List<Integer> groupIds = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds.add(group.getId());
			}
			params.put("groups", groupIds);
			params.put("hallcode", this.getUser(request).getOrganizationId());
			product = productService.findById(params);
		}

		if (StringUtils.isNotBlank(name)) {
			product.setName(name);
		}
		// --产品类型判断:非0,非空,[1-8]
		/**
		 * --1:数量,2:按时间,3:年卡,4:季卡,5:月卡,6:半月卡,7:按金额,8:普通消费 3,4,5,6,按照实际消费时间计算起始日期
		 */
		if (StringUtils.isNotBlank(type) && !"0".endsWith(type)) {
			Integer tp = Integer.valueOf(type);
			product.setType(tp);
			if (tp == 101) {
				if (StringUtils.isNotBlank(counts)) {
					try {
						Integer count = Integer.valueOf(counts);
						product.setCounts(count);
					} catch (Exception e) {
						model.put("msg", "次数格式不符合规范!");
						return "product_add";
					}
				}
			} else if (tp == 102) {
				if (StringUtils.isNotBlank(beginTime)) {

					product.setBeginTime(dtu.parse(beginTime));
				}
				if (StringUtils.isNotBlank(endTime)) {
					product.setEndTime(dtu.parse(endTime));
					// --产品到期时间提醒(根据结束日期判断)
					product.setExpiringThd(getExpiringDate(
							product.getEndTime(), 10));
				}
			}
		}
		if (StringUtils.isNotBlank(price)) {
			try {
				product.setPrice(Double.valueOf(price));
				map.put("price", price);
			} catch (Exception e) {
				model.put("msg", "价格格式不符合规范!");
				return "product_add";
			}
		} else {
			product.setPrice(0.0);
		}

		// 每周限制几次使用
		String limitOfWeek = request.getParameter("limitOfWeek");
		if (StringUtils.isNotBlank(limitOfWeek)) {
			Integer intLimit = Integer.valueOf(limitOfWeek);
			product.setLimitOfWeek(intLimit);
		}

		if (StringUtils.isNotBlank(remarks)) {
			product.setRemarks(remarks);
			map.put("remarks", remarks);
		}
		if (StringUtils.isNotBlank(productId)) {
			if (productService.update(product) > 0) {
				model.put("msg", "xps");
			} else {
				model.put("msg", "xpf");
				return "product_edit";
			}
		} else {
			if (productService.save(product) > 0) {
				model.put("msg", "cps");
			} else {
				model.put("msg", "cpf");
				return "product_add";
			}
		}
		return "redirect:searchProducts.jhtml";
	}

	/**
	 * 即将过期的时间
	 * 
	 * @param date
	 * @param days
	 * @return
	 */
	public String getExpiringDate(Date endTime, int days) {
		String dt = dtu.format(new Date(endTime.getTime() - days * 24 * 60 * 60
				* 1000), "yyyy-MM-dd hh:mm");
		return dt;
	}

	/** 跳转到个人购买的产品页面 */
	@RequestMapping(value = "/toMemberProduct.jhtml")
	public String searchProduct(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);
		Map<String, Object> map = new HashMap<String, Object>();
		int start = 0, startPR = 0, startP = 0, proOPage = 1;
		int limit = 6;
		int memberId = 0;
		User user = this.getUser(request);
		String pageNo = request.getParameter("pageNo");
		String pagePRNo = request.getParameter("pagePRNo");
		String pagePNo = request.getParameter("pagePNo");
		String pageProONo = request.getParameter("pageProONo");
		String pageSize = request.getParameter("pageSize");

		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}

		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		if (StringUtils.isNotBlank(pagePRNo)) {
			startPR = (Integer.parseInt(pagePRNo) - 1) * limit;
		}
		if (StringUtils.isNotBlank(pagePNo)) {
			startP = (Integer.parseInt(pagePNo) - 1) * limit;
		}

		if (StringUtils.isNotBlank(pageProONo)) {
			proOPage = Integer.parseInt(pageProONo);
		}
		String strMemberId = request.getParameter("memberId");
		if (strMemberId != null) {
			memberId = Integer.parseInt(strMemberId);
		}

		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds1 = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds1.add(group.getId());
		}
		map1.put("groups", groupIds1);
		map1.put("id", memberId);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = this.memberService.findById(map1);

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Product> productList = this.productService
				.findProductAvailable(startP, 6, map);

		map.put("memberId", strMemberId);
		map.put("buyerId", strMemberId);
		map.put("hallCode", user.getOrganizationId());

		int pageOCount = 0, orderCount = 0;
		orderCount = this.orderService.getOrderEnabledCountByMemberId(map);
		pageOCount = (orderCount - 1) / limit + 1;

		if (proOPage > pageOCount) {
			proOPage = pageOCount;
		}

		// --购买的产品
		PaginatedList<ProductUsedInfo> pl = this.productRemainingService
				.findMemberProductsUsed(start, limit, map);

		// --购买下单记录
		PaginatedList<TinyOrderModel> proOrders = this.orderService
				.findAllBuyRecord(proOPage, limit, map);

		// --查询会员购买的产品的使用情况
		PaginatedList<ProductUsedInfo> productUsedInfos = this.productRemainingService
				.findMemberProductsUsed(startPR, limit, map);

		// 查找购买产品的负责人,供购买时选择...
		List<GroupUserModel> respors = userService.findUsersByGroupId("4", this
				.getUser(request).getOrganizationId());
		model.put("responsibleList", respors);
		model.put("pl", pl);
		model.put("productUsedInfos", productUsedInfos);
		model.put("productList", productList);
		model.put("member", member);
		model.put("proOrders", proOrders);

		model.put("resporsId", this.getUser(request).getId());

		String buy = request.getParameter("buy");
		if ("true".equals(buy)) {
			model.put("buyAtSameTime", true);
		}
		return "product_detail";
	}

	/**
	 * 导出合同模板pdf
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/exportContractPdf.jhtml", method = RequestMethod.POST)
	public void exportContractPdf(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {

		String orderId = request.getParameter("orderId");
		if (StringUtils.isBlank(orderId)) {
			return;
		}

		Order order = this.orderService.findById(Integer.valueOf(orderId));
		OrderDetail od = order.getOrderDetails().get(0);
		Product pdt = od.getProduct();

		String cardid = order.getMember().getCardnumber();// 会员卡号
		String name = order.getMember().getName();// 会员真实姓名
		String sex = order.getMember().getSex();// 性别
		String address = order.getMember().getAddress();// 地址
		SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
		String birthday = "";// 出生日期
		if (order.getMember().getBirthday() != null) {
			birthday = sdt.format(order.getMember().getBirthday());
		}
		String mobile = order.getMember().getPhone();// 移动电话
		String people_id = order.getMember().getIdentity();// 身份证号
		String email = order.getMember().getEmail();// 电子邮件
		String cardtype = pdt.getName();// 卡种
		String cardfrom = "";// 有效期从
		if (od.getProductRemaining() != null
				&& od.getProductRemaining().getBeginTime() != null) {
			cardfrom = sdt.format(od.getProductRemaining().getBeginTime());
		}
		String cardto = "";// 有效期到
		if (od.getProductRemaining() != null
				&& od.getProductRemaining().getEndTime() != null) {
			cardto = sdt.format(od.getProductRemaining().getEndTime());
		}

		String pay = order.getActualMoney().toString();// 支付金额
		int intPaytype = order.getPayType();// 支付方式
		String paytype = "现金";
		if (intPaytype == 1) {
			paytype = "现金";
		} else if (intPaytype == 2) {
			paytype = "刷卡";
		} else if (intPaytype == 3) {
			paytype = "转账";
		} else if (intPaytype == 4) {
			paytype = "支票";
		} else if (intPaytype == 2) {
			paytype = "银联";
		}

		String contract_date = "";// 签约日期
		if (order.getInputTime() != null) {
			contract_date = sdt.format(order.getInputTime());
		}

		String jasperFolder = request.getServletContext().getRealPath(
				"app/admin/resources/jasper");
		String jasperFile = jasperFolder + "/contract.jasper";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("m_cardid", cardid);
		params.put("m_name", name);
		params.put("m_sex", sex);
		params.put("m_address", address);
		params.put("m_birthday", birthday);
		params.put("m_mobile", mobile);
		params.put("m_people_id", people_id);
		params.put("m_email", email);
		params.put("m_cardtype", cardtype);
		params.put("m_cardfrom", cardfrom);
		params.put("m_cardto", cardto);
		params.put("m_pay", pay);
		params.put("m_paytype", paytype);
		params.put("m_contract_date", contract_date);

		String fileName = name + "-合同套打模板.pdf";

		String agent = request.getHeader("User-Agent").toLowerCase();
		String browserType = FrontUtil.getBrowserType(agent);

		try {
			if (browserType.startsWith("ie")) {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else {
				fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException e1) {
			throw new RuntimeException("不支持的编码格式异常");
		}
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "inline; filename="
				+ fileName);
		response.setContentType("application/pdf");

		try {
			JasperRunManager.runReportToPdfStream(new FileInputStream(
					jasperFile), response.getOutputStream(), params,
					new JREmptyDataSource());
		} catch (Exception e) {
			throw new RuntimeException("导出pdf时异常", e);
		}

		try {
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			throw new RuntimeException("导出pdf时，IO异常");
		}
	}

	/** 购买产品 */
	@RequestMapping(value = "/buyProduct.jhtml")
	public void buyProduct(String memberId, String productId, String sellerId,
			String buyType, String earnest, String discount, String beginDate,
			String endDate, Integer payType, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		this.initFrontHeader(request, model);
		String msg = "{'success': 'false', 'msg': '产品购买失败!'}";
		// --定金
		Double dj = 0.00d;
		// --商品总价
		Double zje = 0.00d;
		// --余额
		Double ye = 0.00d;
		Double tempye = 0.00d;

		Double toScore = 0.0d;
		if (StringUtils.isBlank(sellerId)) {
			msg = "{'success': 'false', 'msg': '负责人不能为空!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		Double discounts = 0.0;
		if (StringUtils.isNotBlank(discount)) {
			try {
				discounts = Double.parseDouble(discount);
			} catch (NumberFormatException e) {
				msg = "{'success': 'false', 'msg': '折扣格式不正确!'}";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			}
		}

		// 查找会员
		Member member = new Member();
		List<Product> listProduct = new ArrayList<Product>();
		List<ProductRemaining> prs = new ArrayList<ProductRemaining>();
		List<OrderDetail> listOD = new ArrayList<OrderDetail>();
		Order order = new Order();

		order.setState(1);
		Product product = null;
		OrderDetail oD = null;
		// --查询会员账户金额
		Remaining remaining = new Remaining();
		if (StringUtils.isNotBlank(memberId)) {
			Integer memId = Integer.valueOf(memberId);
			Map<String, Object> map1 = new HashMap<String, Object>();
			List<Integer> groupIds1 = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds1.add(group.getId());
			}
			map1.put("groups", groupIds1);
			map1.put("id", memId);
			map1.put("hallcode", this.getUser(request).getOrganizationId());
			member = this.memberService.findById(map1);
			remaining = remainingService.findById(memId);
			// --会员账户余额
			if (remaining != null) {
				ye = remaining.getRemaining();
				tempye = ye;
			}
		} else {
			msg = "{'success': 'false', 'msg': '会员不存在!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (StringUtils.isNotBlank(productId)
				&& StringUtils.isNotBlank(memberId)) {
			String proIds[] = productId.split(",");
			for (String proId : proIds) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("productId", proId);
				List<Integer> groupIds = new ArrayList<Integer>();
				for (Group group : this.getUser(request).getGroups()) {
					groupIds.add(group.getId());
				}
				params.put("groups", groupIds);
				params.put("hallcode", this.getUser(request)
						.getOrganizationId());
				product = this.productService.findById(params);
				listProduct.add(product);
			}
			// 计算总金额
			for (Product prd : listProduct) {
				oD = new OrderDetail();
				oD.setOrder(order);
				oD.setProduct(prd);
				listOD.add(oD);
				zje = NumberUtils.add(zje, prd.getPrice());
			}
		}
		order.setType(buyType);
		if ("定金".equals(buyType)) {
			if (StringUtils.isBlank(earnest)) {
				msg = "{'success': 'false', 'msg': '定金不能为空!'}";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			} else {
				// --定金
				dj = Double.valueOf(earnest);
				if (dj <= 0) {
					msg = "{'success': 'false', 'msg': '定金不能小于等于零!'}";
					WebAppUtils.ajaxResponse(response, msg);
					return;
				} else {
					if (ye < dj) {
						msg = "{'success': 'false', 'msg': '账户余额不足,请及时充值!'}";
						WebAppUtils.ajaxResponse(response, msg);
						return;
					} else {
						// --要定金下的余额。
						ye = NumberUtils.sub(ye, dj);
						order.setActualMoney(dj);
					}
				}
			}
			order.setDiscount(0.0);
		} else {
			// --产品折后价
			Double spzhj = NumberUtils.sub(zje, discounts);
			if (ye < spzhj) {
				// 直接创建一条充值记录
				Double stillNeed = NumberUtils.sub(spzhj, ye);
				Recharge recharge = new Recharge();
				recharge.setMember(member);
				recharge.setRecharge(stillNeed);
				recharge.setMoney(stillNeed);

				User user = this.getUser(request);
				Recharge rec = new Recharge();
				rec.setCreateTime(dtu.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				rec.setRecharge(stillNeed);
				rec.setMoney(stillNeed);
				rec.setRemarks("创建会员时同时购买产品");
				rec.setMember(member);
				rec.setUser(user);
				String type = request.getParameter("payType");
				rec.setType(Integer.valueOf(type));
				rec.setLogType("充值");
				rec.setOrganizationId(member.getOrganizationId());
				this.rechargeService.insert(rec);// 存入充值记录
				ye = spzhj;
			}

			// --总额后的余额。
			ye = NumberUtils.sub(ye, spzhj);
			order.setActualMoney(spzhj);
			order.setDiscount(discounts);
			Double money = zje - discounts;
			Site site = systemService.getSystem();
			toScore = money / site.getToScore();
		}

		if ("新销售".equals(buyType)) {
			for (int k = 0; k < listProduct.size(); k++) {
				ProductRemaining pr = new ProductRemaining();
				Product p = listProduct.get(k);
				Integer proType = p.getType();
				// --次卡
				if (proType == 101) {
					pr.setCounts(p.getCounts());
					// --时间卡
				} else if (proType == 102) {
					pr.setBeginTime(p.getBeginTime());
					pr.setEndTime(p.getEndTime());
				}
				pr.setMemberId(Integer.valueOf(memberId));
				pr.setProductId(p.getProductId());
				if (StringUtils.isNotBlank(beginDate)
						&& StringUtils.isNotBlank(endDate)) {
					pr.setBeginTime(DateTimeUtils.getInstance().parse(
							beginDate, "yyyy-MM-dd"));
					pr.setEndTime(DateTimeUtils.getInstance().parse(endDate,
							"yyyy-MM-dd"));
				}
				if (!productRemainingService.saveProductRemaining(pr)) {
					msg = "{'success': 'false', 'msg': '创建会员产品明细失败!'}";
					WebAppUtils.ajaxResponse(response, msg);
					return;
				}
				prs.add(pr);
			}

			Status status = member.getChildStatus();
			if (status != null) {
				status = status.getParent();
				if (status != null) {
					if (!"正式会员".equals(status.getName())) {
						member.setSubstatus("0020");
					}
				} else {
					member.setSubstatus("0020");
				}
			} else {
				member.setSubstatus("0020");
			}

			Iterator<OrderDetail> iterator = listOD.iterator();
			Iterator<ProductRemaining> it = prs.iterator();

			while (iterator.hasNext()) {
				iterator.next().setProRemainId(it.next().getId());
			}
		}

		// --2.修改账户余额
		if (ye != tempye) {
			remaining.setMemberId(Integer.valueOf(memberId));
			remaining.setRemaining(ye);

			int score = toScore.intValue();
			order.setScore(score);
			Integer yscore = remaining.getScore();
			if (yscore == null) {
				yscore = 0;
			}
			score += yscore;
			remaining.setScore(score);

			// --是否修改账户余额成功
			if (!remainingService.updateRemainingById(remaining)) {
				msg = "{'success': 'false', 'msg': '余额更新失败!'}";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			}
		}

		// 填充数据
		order.setMember(member);
		order.setInputTime(new Date());
		order.setMoney(zje);
		order.setOrderDetails(listOD);
		order.setPayType(payType);

		User user = this.userService.findById(sellerId);
		order.setSeller(user);

		int i = this.orderService.save(order);
		if (i == 0) {
			msg = "{'success': 'false', 'msg': '订单保存失败!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		} else {
			int m = 0;
			if (listOD.size() > 0) {
				for (OrderDetail od : listOD) {
					od.setOrder(order);
					m = this.orderDetailService.save(od);
					if (m <= 0) {
						msg = "{'success': 'false', 'msg': '订单详情创建失败!'}";
						WebAppUtils.ajaxResponse(response, msg);
						return;
					}
				}
			}
			if (memberService.updateMember(member)) {
				msg = "{'success': 'true', 'msg': '更新会员状态成功!'}";
			} else {
				msg = "{'success': 'false', 'msg': '更新会员状态失败!'}";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 查找分页产品 */
	@RequestMapping(value = "findProductInpage.jhtml")
	public void findProductInPage(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		int start = 0, limit = 10;
		String pageNo = request.getParameter("pageNo");

		int page = 1;
		if (pageNo != null) {
			try {
				page = Integer.parseInt(pageNo);
			} catch (NumberFormatException e) {
				page = 1;
			}

			start = (page - 1) * limit;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);
		params.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Product> productList = this.productService
				.findProductAvailable(start, limit, params);

		if (productList == null || productList.size() <= 0) {
			msg = "{'success': 'false', 'msg': '未找到产品'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		StringBuffer buffer = new StringBuffer("[");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (Product product : productList) {
			buffer.append("{");
			buffer.append("'productId':'" + product.getProductId() + "',");
			buffer.append("'name':'" + product.getName() + "',");
			buffer.append("'type':'" + product.getType() + "',");
			buffer.append("'price':'" + product.getPrice() + "',");
			if (product.getBeginTime() == null)
				buffer.append("'beginTime':'',");
			else
				buffer.append("'beginTime':'"
						+ sdf.format(product.getBeginTime()) + "',");
			if (product.getEndTime() == null)
				buffer.append("'endTime':''},");
			else
				buffer.append("'endTime':'" + sdf.format(product.getEndTime())
						+ "'},");
		}

		String str = buffer.toString();
		str = str.substring(0, str.length() - 1);
		str += "]";
		msg = "{'success': 'true', 'items':" + str + "}";

		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 会员购买页面查找产品 */
	@RequestMapping(value = "findMemberInfoProductInpage.jhtml")
	public void findMemberInfoInPage(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		int start = 0, limit = 6;
		String pageNo = request.getParameter("pageNo");

		int page = 1;
		if (pageNo != null) {
			try {
				page = Integer.parseInt(pageNo);
			} catch (NumberFormatException e) {
				page = 1;
			}
			start = (page - 1) * limit;
		}

		String name = request.getParameter("productName");
		String type = request.getParameter("productType");
		String price = request.getParameter("productPrice");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		map.put("type", type);
		map.put("price", price);
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Product> productList = this.productService
				.findMemberInfoInPage(map, start, limit);

		if (productList == null || productList.size() <= 0) {
			msg = "{'success': false, 'msg': '未找到产品'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		StringBuffer buffer = new StringBuffer("[");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (Product product : productList) {
			buffer.append("{");
			buffer.append("'productId':'" + product.getProductId() + "',");
			buffer.append("'name':'" + product.getName() + "',");
			buffer.append("'type':'" + product.getType() + "',");
			buffer.append("'price':'" + product.getPrice() + "',");
			if (product.getBeginTime() == null)
				buffer.append("'beginTime':'',");
			else
				buffer.append("'beginTime':'"
						+ sdf.format(product.getBeginTime()) + "',");
			if (product.getEndTime() == null)
				buffer.append("'endTime':''},");
			else
				buffer.append("'endTime':'" + sdf.format(product.getEndTime())
						+ "'},");
		}

		String str = buffer.toString();
		str = str.substring(0, str.length() - 1);
		str += "]";
		msg = "{'success':true, 'totalPages': "
				+ productList.getPager().getCountOfTotalPages()
				+ ", 'totalResults': "
				+ productList.getPager().getCountOfTotalResults()
				+ ", 'items':" + str + "}";

		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 导出产品记录 */
	@RequestMapping(value = "/exportProductList.jhtml", method = RequestMethod.POST)
	public void exportProductList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {

		int start = 0;
		// 产品的查询条件
		String productName = request.getParameter("productName");
		String productType = request.getParameter("productType");
		String startdate1 = request.getParameter("startdate1");
		String startdate2 = request.getParameter("startdate2");
		String enddate1 = request.getParameter("enddate1");
		String enddate2 = request.getParameter("enddate2");

		Map<String, Object> params = new HashMap<String, Object>();

		if (pageSize == null) {
			pageSize = 10;
		}

		if (pageNo != null) {
			start = (pageNo - 1) * pageSize;
		}

		if (StringUtils.isNotBlank(productName)) {
			params.put("name", productName);
		}
		if (StringUtils.isNotBlank(productType)) {
			params.put("type", productType);
		}

		if (StringUtils.isNotBlank(startdate1)) {
			params.put("startdate1", startdate1);
		}

		if (StringUtils.isNotBlank(enddate1)) {
			params.put("enddate1", enddate1);
		}

		if (StringUtils.isNotBlank(startdate2)) {
			params.put("startdate2", startdate2);
		}

		if (StringUtils.isNotBlank(enddate2)) {
			params.put("enddate2", enddate2);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);
		params.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Product> pl = productService.findInPage(params, start,
				Integer.MAX_VALUE);
		ProductExportTemplate template = new ProductExportTemplate(pl);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response,
				"产品记录信息表.xlsx");
		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 导出购买记录 */
	@RequestMapping(value = "/exportOrderList.jhtml", method = RequestMethod.POST)
	public void exortOrderList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {

		// 购买记录的查询条件
		String orderProName = request.getParameter("orderProName");
		String orderProType = request.getParameter("orderProType");
		String buyStartDate = request.getParameter("buyStartDate");
		String buyEndDate = request.getParameter("buyEndDate");
		String buyerId = request.getParameter("buyerId");
		String sellerId = request.getParameter("sellerId");
		String orderType = request.getParameter("orderType");

		Map<String, Object> params = new HashMap<String, Object>();

		if (pageNo == null) {
			pageNo = 1;
		}

		if (pageSize == null) {
			pageSize = 10;
		}
		if (StringUtils.isNotBlank(orderProName)) {
			params.put("name", orderProName);
		}
		if (StringUtils.isNotBlank(orderProType)) {
			params.put("type", orderProType);
		}
		if (StringUtils.isNotBlank(sellerId)) {
			params.put("sellerId", sellerId);
		}
		if (StringUtils.isNotBlank(buyerId)) {
			params.put("buyerId", buyerId);
		}
		if (StringUtils.isNotBlank(buyStartDate)) {
			params.put("buyStartDate", buyStartDate);
		}
		if (StringUtils.isNotBlank(buyEndDate)) {
			params.put("buyEndDate", buyEndDate);
		}
		if (StringUtils.isNotBlank(orderType)) {
			params.put("orderType", orderType);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);

		PaginatedList<TinyOrderModel> pl = this.orderService.findAllBuyRecord(
				pageNo, Integer.MAX_VALUE, params);
		TinyOrderExportTemplate template = new TinyOrderExportTemplate(pl);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response,
				"购买记录信息表.xlsx");
		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/** 导出消费信息 */
	@RequestMapping(value = "/exportConsumeList.jhtml", method = RequestMethod.POST)
	public void exportConsumeList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, Integer pageNo,
			Integer pageSize) {
		String classId = request.getParameter("sltClassId");
		String productId = request.getParameter("productId");
		String memberId = request.getParameter("memberId");
		String areaId = request.getParameter("areaId");
		String consumeTimeFrom = request.getParameter("consumeTimeFrom");
		String consumeTimeTo = request.getParameter("consumeTimeTo");
		String scheduleTimeFrom = request.getParameter("scheduleTimeFrom");
		String scheduleTimeTo = request.getParameter("scheduleTimeTo");

		Map<String, Object> params = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(classId)) {
			params.put("classId", classId);
		}

		if (StringUtils.isNotBlank(productId)) {
			params.put("productId", productId);
		}

		if (StringUtils.isNotBlank(memberId)) {
			params.put("memberId", memberId);
		}

		if (StringUtils.isNotBlank(areaId)) {
			params.put("areaId", areaId);
		}

		if (StringUtils.isNotBlank(consumeTimeFrom)) {
			params.put("consumeTimeFrom", consumeTimeFrom);
		}

		if (StringUtils.isNotBlank(consumeTimeTo)) {
			params.put("consumeTimeTo", consumeTimeTo);
		}

		if (StringUtils.isNotBlank(scheduleTimeFrom)) {
			params.put("scheduleTimeFrom", scheduleTimeFrom);
		}
		if (StringUtils.isNotBlank(scheduleTimeTo)) {
			params.put("scheduleTimeTo", scheduleTimeTo);
		}

		if (pageNo == null) {
			pageNo = 1;
		}

		if (pageSize == null) {
			pageSize = 10;
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		params.put("groups", groupIds);

		PaginatedList<ConsumeHistoryModel> consumeList = this.productService
				.findAllConsumeHistory(params, pageNo, Integer.MAX_VALUE);
		ConsumeHistoryExportTemplate template = new ConsumeHistoryExportTemplate(
				consumeList);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response,
				"消费记录信息表.xlsx");
		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获得产品价格
	 * */
	@RequestMapping(value = "getProductPrice.jhtml")
	public void getPrice(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "";
		String strId = request.getParameter("id");

		if (StringUtils.isBlank(strId)) {
			msg = "{'success':false, 'msg':'产品编号不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		int Id = 0;
		try {
			Id = Integer.parseInt(strId);
		} catch (NumberFormatException e) {
			msg = "{'success':false, 'msg':'产品编号格式不正确！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productId", Id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		Product p = this.productService.findById(map);

		if (p == null) {
			msg = "{'success':false, 'msg':'未找到该产品！'}";
		} else {
			String json = JSON.toJSONString(p);
			msg = "{'success':true, 'item':" + json + "}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public OrderDetailService getOrderDetailService() {
		return orderDetailService;
	}

	public void setOrderDetailService(OrderDetailService orderDetailService) {
		this.orderDetailService = orderDetailService;
	}

	public ProductRemainingService getProductRemainingService() {
		return productRemainingService;
	}

	public void setProductRemainingService(
			ProductRemainingService productRemainingService) {
		this.productRemainingService = productRemainingService;
	}

	public RemainingService getRemainingService() {
		return remainingService;
	}

	public void setRemainingService(RemainingService remainingService) {
		this.remainingService = remainingService;
	}

	public ClazzService getClazzService() {
		return clazzService;
	}

	public void setClazzService(ClazzService clazzService) {
		this.clazzService = clazzService;
	}

	public StatusService getStatusService() {
		return statusService;
	}

	public void setStatusService(StatusService statusService) {
		this.statusService = statusService;
	}

	public SystemService getSystemService() {
		return systemService;
	}

	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}
}
